package com.example.ch3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbDao {
	private static DbDao op;
	// 数据库连接
	private Connection conn;
	// 数据库驱动
	private String driver;
	// 数据库服务的url
	private String url;
	// 数据库用户名
	private String username;
	// 数据库密码
	private String pass;

	// 构造器私有，准备做成单态模式
	private DbDao() {

	}

	// 带参数的构造器
	private DbDao(String driver, String urI, String username, String pass) throws Exception {
		this.driver = driver;
		this.url = urI;
		this.username = username;
		this.pass = pass;
		Class.forName(driver);
		conn = DriverManager.getConnection(url, username, pass);
	}

	public static DbDao getOp() {
		return op;
	}

	public static void setOp(DbDao op) {
		DbDao.op = op;
	}

	public Connection getConn() {
		return conn;
	}

	public void setConn(Connection conn) {
		this.conn = conn;
	}

	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	// 获取数据库连接
	public void getConnection() throws Exception {
		if (conn == null) {
			Class.forName(this.driver);
			conn = DriverManager.getConnection(this.url, this.username, this.pass);
		}
	}

	// 静态方法，返回DbDao实例
	public static DbDao instance() {
		if (op == null) {
			op = new DbDao();
		}
		return op;
	}

	// 静态方法，返回DbDao 实例
	public static DbDao instance(String driver, String url, String username, String pass) throws Exception {
		if (op == null) {
			op = new DbDao(driver, url, username, pass);
		}
		return op;
	}

	// 数据库访问操作，执行插入操作
	public boolean insert(String sql) throws Exception {
		// 初始化数据库连接
		getConnection();
		// 创建Statement 对象
		Statement stmt = this.conn.createStatement();
		if (stmt.executeUpdate(sql) != 1) {
			return false;
		}
		return true;
	}

	// 数据库访问操作，执行查询操作
	public ResultSet query(String sql) throws Exception {
		// 初始化数据库连接
		getConnection();
		// 创建Statement对象
		Statement stmt = this.conn.createStatement();
		return stmt.executeQuery(sql);
	}

	// 数据库访问操作，执行删除操作
	public void delete(String sql) throws Exception {
		// 初始化数据库连接
		getConnection();
		// 创建Statement对象
		Statement stmt = this.conn.createStatement();
		stmt.executeUpdate(sql);
	}

	// 数据库访问操作，执行更新操作
	public void update(String sql) throws Exception {
		// 初始化数据库连接
		getConnection();
		// 创建Statement对象
		Statement stmt = this.conn.createStatement();
		stmt.executeUpdate(sql);
	}
}
